<template>
	<view id="form">
		<u--form :model="form" :rules="rules" ref="form1">
			<u-form-item labelWidth="70" label="巡检类型" prop="typeName" borderBottom @click="showType = true">
				<u--input v-model="form.typeName" disabled disabledColor="#fff" placeholder="请选择巡检类型" border="none">
				</u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item labelWidth="70" label="项目名称" required prop="projectName" borderBottom>
				<str-autocomplete :importvalue="form.projectName" :list="projectList" :label="labelFormatter"
					@select="onSelect" @change="onInputChange" highlightColor="#FF0000"></str-autocomplete>
				<u-button class="btn-add" plain icon="plus" type="primary" size="mini" slot="right"
					@click="toAddProject"></u-button>
				<!-- <u-icon slot="right" name="plus" @click="toAddProject"></u-icon> -->
			</u-form-item>
			<u-form-item labelWidth="70" label="所属区域" required prop="areaName" @click="onGetArea">
				<u--input v-model="form.areaName" disabled disabledColor="#fff" placeholder="选择所属区域" border="none">
				</u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item labelWidth="70" label="定位" required prop="locationAddr" borderBottom @click="onShowMapWrap">
				<u--input v-model="form.locationAddr" disabled disabledColor="#fff" placeholder="选择定位" border="none">
				</u--input>
				<u-icon slot="right" name="map-fill"></u-icon>
			</u-form-item>
			
			<u-form-item labelWidth="70" label="施工围挡">
				<u-upload :capture="['camera']" :fileList="encList" @delete="deletePic('enc')" name="enc" multiple
					:width="40" :height="40" :maxCount="5" useBeforeRead @beforeRead="beforeUpload" @afterRead="fileUpload">
				</u-upload>
			</u-form-item>
			<u-form-item labelWidth="70" label="物料覆盖">
				<u-upload :capture="['camera']" :fileList="covList" @delete="deletePic('cov')" name="cov" multiple
					:width="40" :height="40" :maxCount="5" @afterRead="fileUpload"></u-upload>
			</u-form-item>
			<u-form-item labelWidth="70" label="车辆冲洗">
				<u-upload :capture="['camera']" :fileList="washList" @delete="deletePic('wash')" name="wash" multiple
					:width="40" :height="40" :maxCount="5" @afterRead="fileUpload"></u-upload>
			</u-form-item>
			<u-form-item labelWidth="90" label="地面硬化">
				<u-upload :capture="['camera']" :fileList="hardList" @delete="deletePic('hard')" name="hard" multiple
					:width="40" :height="40" :maxCount="5" @afterRead="fileUpload"></u-upload>
			</u-form-item>
			<u-form-item labelWidth="90" label="湿法作业">
				<u-upload :capture="['camera']" :fileList="workList" @delete="deletePic('work')" name="work" multiple
					:width="40" :height="40" :maxCount="5" @afterRead="fileUpload"></u-upload>
			</u-form-item>
			<u-form-item labelWidth="90" label="渣土车密闭">
				<u-upload :capture="['camera']" :fileList="carList" @delete="deletePic('car')" name="car" multiple
					:width="40" :height="40" :maxCount="5" @afterRead="fileUpload"></u-upload>
			</u-form-item>
			<u-form-item labelWidth="70" label="其他">
				<u-upload :capture="['camera']" :fileList="otherList" @delete="deletePic('other')" name="other" multiple
					:width="40" :height="40" :maxCount="5" @afterRead="fileUpload"></u-upload>
			</u-form-item>
			<u-form-item labelWidth="70" label="备注" prop="remark">
				<u-textarea v-model="form.remark" placeholder="输入备注" autoHeight></u-textarea>
			</u-form-item>
			<u-form-item labelWidth="70" label="有无问题" @click="showProblem = true">
				<u--input v-model="form.isProblem1" disabled disabledColor="#fff" placeholder="请选择有无问题" border="none">
				</u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<view v-if="form.isProblem === 1">
				<u-divider text="问题详情" textPosition="center"></u-divider>
				<u-form-item labelWidth="70" label="问题等级" @click="showProbLev = true" required prop="problemLevelName">
					<u--input v-model="form.problemLevelName" disabled disabledColor="#fff" placeholder="请选择问题等级"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item labelWidth="70" label="图片">
					<u-upload :capture="['camera']" :fileList="proList" @delete="deletePic('pro')" name="pro" multiple
						:width="40" :height="40" :maxCount="5" @afterRead="fileUpload"></u-upload>
				</u-form-item>
				<u-form-item labelWidth="70" label="视频">
					<u-upload :capture="['camera']" :maxCount="1" accept="video" :fileList="videoList"
						@delete="deletePic('video')" name="video" multiple :width="40" :height="40"
						@afterRead="videoUpload"></u-upload>
				</u-form-item>
				<u-form-item labelWidth="70" label="问题描述" required prop="problemDescribe">
					<u-textarea v-model="form.problemDescribe" placeholder="输入问题描述"></u-textarea>
				</u-form-item>
				<u-form-item labelWidth="100" label="是否需要整改" @click="showRectify = true">
					<u--input v-model="form.isRectify1" disabled disabledColor="#fff" placeholder="请选择是否需要整改"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<view v-if="form.isRectify === 1">
					<u-form-item labelWidth="70" label="整改期限" required prop="rectifyTime" @click="showCalendar = true">
						<u--input v-model="form.rectifyTime" disabled disabledColor="#fff" placeholder="请选择整改期限"
							border="none"></u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item labelWidth="70" label="整改要求">
						<u-textarea v-model="form.rectifyDemand" placeholder="输入整改要求"></u-textarea>
					</u-form-item>
				</view>
			</view>
		</u--form>
		<view class="submit-btn">
<!-- 			<u-button type="primary" :disabled="submitDisabled" :loading="submitLoading" :text="submitText"
				@click="onSubmit"></u-button> -->
			<text class="btn-add" :loading="submitLoading" @click="onSubmit">{{ submitText }}</text>
		</view>
		<u-picker closeOnClickOverlay :show="showArea" :loading="cityLoading" ref="cityPicker" :columns="cityColumns"
			@confirm="onCityConfirm" @change="onChangeCity" @cancel="onCityCancel" @close="onCloseCity"
			keyName="areaName"></u-picker>
		<u-picker closeOnClickOverlay :show="showProblem" :columns="problemOpts" @cancel="onProCancel"
			@confirm="onProConfirm" @close="onClosePro" keyName="title"></u-picker>
		<u-picker closeOnClickOverlay :show="showProbLev" :columns="problemLevOpts" @cancel="onProbCancel"
			@confirm="onLevConfirm" @close="onCloseProb" keyName="title"></u-picker>
		<u-picker closeOnClickOverlay :show="showRectify" :columns="rectifyOpts" @cancel="onRecCancel"
			@confirm="onRecConfirm" @close="onCloseRec" keyName="title"></u-picker>
		<u-picker closeOnClickOverlay :show="showProject" :columns="projectList" @cancel="onProjCancel"
			@close="onCloseProj" keyName="title"></u-picker>
		<u-picker closeOnClickOverlay :show="showType" :columns="typeOpts" @cancel="onTypeCancel" @close="onCloseType"
			@confirm="onTypeConfirm" keyName="title"></u-picker>
		<!-- 		<u-calendar :show="showCalendar" startText="整改期限" @confirm="confirmCalendar" @close="calendarClose">
		</u-calendar> -->
		<u-datetime-picker :show="showCalendar" v-model="value1" mode="date" @confirm="confirmCalendar"
			@close="calendarClose" @cancel="cancelCalendar"></u-datetime-picker>
		<u-popup :show="showMap" @close="onCloseMap" @open="onShowMap">
			<view class="map_container">
				<map class="map" id="map" :longitude="position.longitude" :latitude="position.latitude"
					:markers="markers" scale="16"></map>
			</view>
			<view class="map_text">
				<view>
					<text class="h1">{{position.name}}</text>
					<text>{{position.desc}}</text>
				</view>
				<view>
					<u-button size="small" type="primary" text="提交" @click="onLocation"></u-button>
				</view>
			</view>
		</u-popup>
		<view style="position: absolute;top: -999999px;">
			<view>
				<canvas style="width: 1000px;height:1000px;" canvas-id="myCanvas"></canvas>
			</view>
		</view>
	</view>
</template>

<script>
	const amapFile = require('@/utils/amap-wx.130')
	const configMap = require('@/utils/config.js')
	import strAutocomplete from '@/components/str-autocomplete/str-autocomplete.vue'
	import config from '@/utils/defaultConfig'
	import {getAreaList,getProjectList} from '@/api/global'
	import {createNo,addPatrol} from '@/api/form'
	import apis from '@/api/apis'
	import {
		ACCESS_TOKEN
	} from '@/store/mutaction-types'

	export default {
		components: {
			strAutocomplete
		},
		data() {
			return {
				myCanvas: null,
				myCtx: null,
				dpr: null,
				submitText: '提交',
				submitLoading: false,
				submitDisabled: false,
				showArea: false,
				cityLoading: false,
				showType: false,
				actions: [],
				cityColumns: [],
				areaList: [],
				maxSize: 500,
				value1: Number(new Date()),
				form: {
					checkNo: '',
					projectName: '',
					projectId: '',
					type: 0,
					typeName: '常规',
					areaId: '',
					areaName: '',
					locationAddr: '',
					isProblem: '',
					isProblem1: '',
					isRectify: '',
					isRectify1: '',
					latitude: '',
					longitude: ''
				},
				rules: {
					projectName: [{
						required: true,
						message: '必须填写项目名称',
						trigger: ['blur']
					}],
					locationAddr: [{
						required: true,
						message: '必须选择定位',
						trigger: ['blur']
					}],
					areaName: [{
						required: true,
						message: '必须选择所属区域',
						trigger: ['blur']
					}],
					problemLevelName: [{
						required: true,
						message: '必须选择问题等级',
						trigger: ['blur']
					}],
					problemDescribe: [{
						required: true,
						message: '必须填写问题描述',
						trigger: ['blur']
					}]
					// rectifyTime: [{
					// 	required: true,
					// 	message: '必须选择整改期限',
					// 	trigger: ['blur']
					// }]
				},
				showProbLev: false,
				problemOpts: [
					config.isProblem
				],
				problemLevOpts: [
					config.problemLevel
				],
				rectifyOpts: [
					config.isRectify
				],
				problemLevOpts: [
					config.problemLevel
				],
				typeOpts: [
					config.type
				],
				showCalendar: false,
				showProblem: false,
				showRectify: false,
				showProject: false,
				labelFormatter: 'projectName',
				projectList: [],
				showMap: false,
				position: {},
				markers: [],
				encList: [],
				covList: [],
				washList: [],
				hardList: [],
				otherList: [],
				workList: [],
				carList: [],
				videoList: [],
				proList: [],
				imageHeader: {
					enc: 'APP_WORK_ENCLOSURE_IMAGE',
					cov: 'APP_MATERIAL_COVER',
					wash: 'APP_VEHICLE_WASHING_IMAGE',
					hard: 'APP_GROUND_HARDENING_IMAGE',
					work: 'APP_WET_WORK_IMAGE',
					car: 'APP_SLAG_CAR_IMAGE',
					other: 'APP_OTHER_IMAGE',
					pro: 'APP_PROBLEM_IMG'
				},
				tempFilePath: '1'
			}
		},
		created() {
			this.getBusinessNo()
		},
		methods: {
			getBusinessNo() {
				createNo().then(res => {
					console.log(1)
					const no = res.data.msg
					const arr = no.split(',')
					this.form.checkNo = arr[0]
					this.form.businessId = arr[1]
				})
				const key = configMap.Config.key
				const myAmapFun = new amapFile.AMapWX({
					key: key
				})
				uni.authorize({
					scope: 'scope.userLocation',
					success: () => {
						uni.getLocation({
							type: 'gcj02',
							success: res => {
								myAmapFun.getRegeo({
									location: `${res.longitude},${res.latitude}`,
									success: add => {
										this.form.locationAddr = add[0].name
										this.form.latitude = res.latitude
										this.form.longitude = res.longitude
									},
									fail: error => {
										console.log(error)
									}
								})
							}
						})
					},
					fail: error => {
						console.log(error)
					}
				})
			},
			typeSelect(e) {

			},
			deletePic(event) {
				this[`${event}List`].splice(event.index, 1)
			},
			onPreviewFull(event) {
				console.log(event)
			},
			onProbCancel() {
				this.showProbLev = false
			},
			onCloseProb() {
				this.showProbLev = false
			},
			onLevConfirm(e) {
				this.form.problemLevel = e.value[0].id
				this.form.problemLevelName = e.value[0].title
				this.showProbLev = false
			},
			onClosePro() {
				this.showProblem = false
			},
			onProCancel() {
				this.showProblem = false
			},
			calendarClose() {
				this.showCalendar = false
			},
			cancelCalendar() {
				this.showCalendar = false
			},
			onProjCancel() {
				this.showProject = false
			},
			onCloseProj() {
				this.showProject = false
			},
			onSelect(opt) {
				console.log(opt)
				this.form.projectId = opt.projectId
				this.form.projectName = opt.projectName
				this.form.areaName = opt.areaFullPath
				this.form.areaId = opt.areaId
			},
			onInputChange(opt) {
				if (opt !== '') {
					getProjectList(opt).then(res => {
						this.projectList = res.data.data
					}).catch(error => {
						console.log(error)
					})
				}
			},
			onChangeCity(e) {
				const {
					columnIndex,
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.cityPicker
				} = e
				if (columnIndex === 0) {
					this.cityLoading = true
					uni.$u.sleep(100).then(res => {
						picker.setColumnValues(1, this.areaList[e.index].children)
						this.cityLoading = false
					})
				}
			},
			onCloseRec() {
				this.showRectify = false
			},
			onGetArea() {
				getAreaList().then(res => {
					this.areaList = res.data.data
					this.cityColumns[0] = this.areaList
					if (this.areaList[0].children.length == 0) {
						this.cityColumns[1] = this.areaList[0]
					} else {
						this.cityColumns[1] = this.areaList[0].children
					}
				}).finally(() => {
					this.showArea = true
				})
			},
			onCityCancel() {
				this.showArea = false
			},
			onCloseCity(e) {
				this.showArea = false
			},
			onCloseMap() {
				this.showMap = false
			},
			confirmCalendar(e) {
				console.log(e)
				this.showCalendar = false
				this.form.rectifyTime = uni.$u.timeFormat(e.value, 'yyyy-mm-dd')
			},
			onShowMap() {},
			onShowMapWrap() {
				uni.authorize({
					scope: 'scope.userLocation',
					success: () => {
						uni.chooseLocation({
							success: res => {
								this.form.longitude = res.longitude
								this.form.latitude = res.latitude
								this.form.locationAddr = res.address
							},
							fail: err => {
								console.log(err)
							}
						})
					}
				})
			},
			// 有无问题
			onProConfirm(e) {
				this.form.isProblem = e.value[0].id
				this.form.isProblem1 = e.value[0].title
				const obj = {
					problemLevelName: [{
						required: true,
						message: '必须选择问题等级',
						trigger: ['change']
					}],
					problemDescribe: [{
						required: true,
						message: '请输入问题描述',
						trigger: ['blur']
					}]
				}
				if (this.form.isProblem === 1) {
					this.rules = Object.assign(obj,this.rules)
				}
				this.showProblem = false
			},
			onSubmit() {
				const app = this
				app.$refs.form1.validate().then(res => {
					app.submitLoading = true
					app.submitText = '上报中'
					addPatrol(app.form).then(res => {
						if (res.data.code === 200) {
							app.submitLoading = false
							app.submitText = '提交'
							uni.$u.toast('提交成功')
							uni.navigateTo({
								url: '/packageD/list/list'
							})
						} else {
							uni.$u.toast(res.msg)
							app.submitLoading = false
							return false
						}
					}).catch(err => {
						uni.$u.toast(err)
						app.submitLoading = false
						return false
					})
				}).catch(errors => {
					app.submitLoading = false
					return false
				})
			},
			onCloseType() {
				this.showType = false
			},
			onTypeCancel() {
				this.showType = false
			},
			onTypeConfirm(e) {
				this.form.type = e.value[0].id
				this.form.typeName = e.value[0].title
				this.showType = false
			},
			onRecConfirm(e) {
				this.form.isRectify = e.value[0].id
				this.form.isRectify1 = e.value[0].title
				this.showRectify = false
			},
			onCityConfirm(e) {
				// 街道办事处等没有二级选择，所以报错
				if (e.value[0].children.length == 0) {
					this.form.areaName = e.value[0].areaName
					this.form.areaId = e.value[0].id
				} else {
					this.form.areaName = e.value[1].areaName
					this.form.areaId = e.value[1].id
				}
				this.showArea = false
			},
			async beforeUpload(event) {
				const data = await this.addMask(event.index, event.file, event.name)
				return data
			},
			async fileUpload(event) {
				const app = this
				this.submitText = '上传中'
				this.submitDisabled = true
				let lists = [].concat(event.file)
				let fileListLen = this[`${event.name}List`].length
				lists.map((item) => {
					this[`${event.name}List`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const url = await this.addMask1(lists[0].url)
					let result = await this.uploadFilePromise(url, this.imageHeader[event.name])
					let item = this[`${event.name}List`][fileListLen]
					this[`${event.name}List`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: 'https://bc-p2-file.oss-cn-zhangjiakou.aliyuncs.com/' + result.msg
					}))
					fileListLen++
				}
			},
			async videoUpload(event) {
				this.submitText = '上传中'
				this.submitDisabled = true
				let lists = [].concat(event.file)
				let fileListLen = this.videoList.length
				lists.map((item) => {
					this.videoList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				const result = await this.uploadFilePromise(lists[0].url, 'APP_PROBLEM_VIDEO')
				const item = this.videoList[0]
				this.videoList.splice(fileListLen, 1, Object.assign(item, {
					status: 'success',
					message: '',
					url: 'https://bc-p2-file.oss-cn-zhangjiakou.aliyuncs.com/' + result.msg
				}))
			},
			uploadFilePromise(url, type) {
				const app = this
				const data = {}
				data['businessId'] = this.form.businessId
				data['businessType'] = type
				return new Promise((resolve, reject) => {
					const a = uni.uploadFile({
						url: 'https://p2.xuzhouzhihui.com/api' + apis.Upload,
						filePath: url,
						name: 'file',
						header: {
							'Authorization': 'Bearer ' + uni.getStorageSync(ACCESS_TOKEN)
						},
						formData: data,
						success: res => {
							setTimeout(() => {
								resolve(JSON.parse(res.data))
								this.submitText = '上报'
								this.submitDisabled = false
							}, 500)
						},
						fail: error => {
							uni.$u.toast(error)
						}
					})
				})
			},
			toAddProject(e) {
				uni.navigateTo({
					url: '../project/project'
				})
			},
			addMask(index, list, name) {
				return new Promise((resolve, reject) => {
					const app = this
					uni.getImageInfo({
						src: list[index].url,
						success: res => {
							const ctx = uni.createCanvasContext('myCanvas')
							ctx.drawImage(list[index].url, 0, 0, res.width, res.height)
							ctx.font = "12px Georgia"
							ctx.fillStyle = "#eee"
							ctx.fillText("地点:" + app.form.locationAddr, 50, 30) // 设置字体
							ctx.fillText("时间:" + new Date().getTime(), 50, 50) // 设置字体
							ctx.fillText("项目:" + app.form.projectName, 50, 70) // 设置字体
							ctx.fillText("定位:" + app.form.locationAddr, 50, 90) // 设置字体
							ctx.draw(false, () => {
								setTimeout(() => {
									uni.canvasToTempFilePath({
										width: res.width,
										height: res.height,
										canvasId: 'myCanvas',
										success: img => {
											this[`${name}List`][index].thumb = img.tempFilePath
											this[`${name}List`][index].url = img.tempFilePath
											uni.saveImageToPhotosAlbum({
												filePath: img.tempFilePath,
												success: isres => {
													resolve(true)
												}
											})
										}
									})
								}, 1000)
							})
						}
					})
				})
			},
			addMask1(url) {
				return new Promise((resolve, reject) => {
					const app = this
					uni.getImageInfo({
						src: url,
						success: res => {
							const ctx = uni.createCanvasContext('myCanvas')
							ctx.drawImage(url, 0, 0, res.width, res.height)
							ctx.font = "12px Georgia"
							ctx.fillStyle = "#eee"
							ctx.fillText("地点:" + app.form.locationAddr, 50, 30) // 设置字体
							ctx.fillText("时间:" + new Date().getTime(), 50, 50) // 设置字体
							ctx.fillText("项目:" + app.form.projectName, 50, 70) // 设置字体
							ctx.fillText("定位:" + app.form.locationAddr, 50, 90) // 设置字体
							ctx.draw(false, () => {
								setTimeout(() => {
									uni.canvasToTempFilePath({
										width: res.width,
										height: res.height,
										canvasId: 'myCanvas',
										success: img => {
											resolve(img.tempFilePath)
										}
									})
								}, 1000)
							})
						}
					})
				})
			},
			async setFilePath (path, name) {
				const tpurl = await this.uploadFilePromise(path, name)
			}
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.form1.setRules(this.rules)
		}
	}
</script>

<style lang="scss" scoped>
	#form {
		padding: 0 20upx 300upx;
	}

	.btn-add {
		width: 40px;
	}

	.map_container {
		width: 750upx;
		height: 750upx;

		#map {
			width: 750upx;
			height: 750upx;
		}
	}

	.map_text {
		background: #fff;
		padding: 0 15px;
		display: flex;
		justify-content: space-between;
		align-items: center;

		text {
			margin: 5px 0;
			display: block;
			font-size: 12px;
		}

		.h1 {
			margin: 15px 0;
			font-size: 15px;
		}
	}

	.submit-btn {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		z-index: 9999;
		background-color: #ffffff;
		height: 100upx;
		.btn-add {
			display: block;
			width: 40%;
			height: 72upx;
			line-height: 72upx;
			background-color: #55aaff;
			margin: 18upx auto;
			border-radius: 40upx;
			text-align: center;
			font-size: 32upx;
			color: #fff;
			background-image: linear-gradient(to right, #2595f9, #1eb8ee);
			box-shadow: 0 1px 4px 0px rgba(30,184,238,0.3);
		}
	}
</style>
